#!/usr/bin/env python3
"""
快速测试脚本 - 验证基本功能
"""
import os
import sys
import tempfile
import shutil

# 添加父目录到路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)

from storage_engine import StorageEngine, CachePolicy
from table_schema import Column, ColumnType

def test_basic_operations():
    """测试基本操作"""
    print("🔍 基本功能测试")
    print("=" * 50)
    
    try:
        # 创建临时数据库目录
        temp_dir = tempfile.mkdtemp()
        db_path = os.path.join(temp_dir, "test_db")
        
        # 初始化存储引擎
        engine = StorageEngine(
            db_path=db_path,
            cache_size=10,
            enable_locking=False
        )
        
        # 1. 创建表
        print("\n1️⃣ 测试创建表...")
        columns = [
            Column("id", ColumnType.INT, primary_key=True),
            Column("name", ColumnType.VARCHAR, length=50),
            Column("age", ColumnType.INT)
        ]
        
        success = engine.create_table("test_table", columns)
        print(f"   创建表结果: {'✅' if success else '❌'}")
        
        if not success:
            print("❌ 创建表失败，测试终止")
            return False
        
        # 2. 插入数据
        print("\n2️⃣ 测试插入数据...")
        test_records = [
            {"id": 1, "name": "Alice", "age": 25},
            {"id": 2, "name": "Bob", "age": 30},
            {"id": 3, "name": "Charlie", "age": 35}
        ]
        
        insert_success = 0
        for record in test_records:
            if engine.insert_record("test_table", record):
                insert_success += 1
                print(f"   ✅ 插入成功: {record}")
            else:
                print(f"   ❌ 插入失败: {record}")
        
        print(f"   插入统计: {insert_success}/{len(test_records)}")
        
        # 3. 查询数据
        print("\n3️⃣ 测试查询数据...")
        all_records = engine.select_records("test_table")
        print(f"   查询到 {len(all_records)} 条记录:")
        for record in all_records:
            print(f"   📝 {record}")
        
        # 4. 更新数据
        print("\n4️⃣ 测试更新数据...")
        updated = engine.update_records(
            "test_table",
            {"id": 2},
            {"name": "Bob Updated", "age": 31}
        )
        print(f"   更新结果: {updated} 条记录")
        
        # 验证更新
        updated_record = engine.select_records("test_table", {"id": 2})
        if updated_record:
            print(f"   更新后的记录: {updated_record[0]}")
        
        # 5. 删除数据
        print("\n5️⃣ 测试删除数据...")
        deleted = engine.delete_records("test_table", {"id": 3})
        print(f"   删除结果: {deleted} 条记录")
        
        # 验证删除
        remaining = engine.select_records("test_table")
        print(f"   剩余记录数: {len(remaining)}")
        
        # 6. 验证主键索引
        print("\n6️⃣ 测试主键索引...")
        # 尝试插入重复主键
        duplicate = engine.insert_record("test_table", {"id": 1, "name": "Duplicate", "age": 40})
        print(f"   插入重复主键结果: {'❌ 正确拒绝' if not duplicate else '❗ 错误允许'}")
        
        # 通过主键查询
        pk_record = engine.select_records("test_table", {"id": 1})
        print(f"   主键查询结果: {pk_record[0] if pk_record else 'Not found'}")
        
        # 清理
        engine.close()
        shutil.rmtree(temp_dir)
        
        print("\n✅ 基本功能测试完成")
        return True
        
    except Exception as e:
        print(f"\n❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = test_basic_operations()
    print(f"\n{'🎉 测试通过' if success else '💥 测试失败'}")
    sys.exit(0 if success else 1)